<!DOCTYPE HTML>
<html>

<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>部门内部培训 react 系列讲义一：React 入门 | DeepThought</title>
  <meta name="google-site-verification" content="Ei6mmDdf-cJwox1RvJOeX8Dc720fqWjZQu-Ww2BjBt4">
  
  <meta name="author" content="积慕">
  
  <meta name="description" content="2018年公司内部培训讲义,react深入浅出,react相关工具,create-react-app使用">
  
  
  <meta name="keywords" content="react,react入门,react深入浅出,上手react,create-react-app,react脚手架,jsx">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
  <meta property="og:title" content="部门内部培训 react 系列讲义一：React 入门">
  <meta property="og:site_name" content="DeepThought">

  
  <meta property="og:image" content>
  

  <link href="https://pic.zhuliang.ltd/favicon.ico" rel="shortcut icon" type="image/x-icon">
  <link rel="alternate" href="/atom.xml" title="DeepThought" type="application/atom+xml">
  <link rel="stylesheet" href="/css/style.css" media="screen" type="text/css">

  <link rel="stylesheet" href="//at.alicdn.com/t/font_1187293_8fec2ou5fyx.css">

  <!-- <link rel="stylesheet" href="//cdn.bootcss.com/highlight.js/9.6.0/styles/github.min.css"> -->
  <!-- <script src="//cdn.bootcss.com/highlight.js/9.6.0/highlight.min.js"></script> -->
  <script src="/js/highlight.min.js"></script>

  <link rel="stylesheet" href="/css/markdown.css">

  <script src="/js/av-min.3.0.4.js"></script>
  <script src="/js/Valine.min.1.3.6.js"></script>

</head></html>

<body>
  <header id="header" class="inner"><div class="alignleft">
  <h1><a href="/">DeepThought</a></h1>
  <h2><a href="/">知识需沉淀，更需分享</a></h2>
</div>
<nav id="main-nav" class="alignright">
  <ul>
    
      <li><a href="/">首页</a></li>
    
      <li><a href="/about">关于我</a></li>
    
      <li><a href="/atom.xml">订阅RSS</a></li>
    
  </ul>
  <div class="clearfix"></div>
</nav>
<div class="clearfix"></div>
        </header>
  <div id="content" class="inner">
    <div id="main-col" class="alignleft"><div id="wrapper"><article class="post">
  
  <div class="post-content">
    <header>
      
        <div class="icon"></div>
      

 
      
  
    <h1 class="title">部门内部培训 react 系列讲义一：React 入门</h1>
  


      
        <time datetime="2018-08-15T04:34:23.000Z">
          create: 2018-08-15 12:34:23 | update: 2018-08-15 21:11:31
            <span style="float: right;">
    <span class="post-count" id="busuanzi_container_page_pv" style="display: inline;">
        
        本文总阅读量: <span id="busuanzi_value_page_pv"></span>&nbsp;次
        <span class="blueSeparate">&nbsp;|&nbsp;</span>
        
        <span class="post-count">文章总字数:&nbsp;2.7k&nbsp;字</span>
    <span class="blueSeparate">&nbsp;|&nbsp;</span>
    <span class="post-count">阅读约需:&nbsp;13&nbsp;分钟</span>
    <br>
</span>
</span>
        </time>
      
            
    </header>
    <div class="entry">
      
      <h1 id="React-入门，based-on-React-16-4-2"><a href="#React-入门，based-on-React-16-4-2" class="headerlink" title="React 入门，based on React.16.4.2"></a>React 入门，based on React.16.4.2</h1><blockquote>
<ul>
<li>react 官网：<a href="https://reactjs.org/" target="_blank" rel="noopener">https://reactjs.org/</a></li>
<li>此文为公司内部培训用 react 讲义内容，适合想学习 react，入门 react 的同学阅读，代码请参加 github：<a href="https://github.com/KedeIT/2018-8.react-demo" target="_blank" rel="noopener">https://github.com/KedeIT/2018-8.react-demo</a></li>
</ul>
</blockquote>
<p>本次教程基于环境、使用工具以及版本：</p>
<ul>
<li>nodejs：8.11.3</li>
<li>react：16.4.2</li>
<li>npm：6.2.0</li>
<li>SPA（单页应用）</li>
<li>create-react-app：2.0.0</li>
</ul>
<a id="more"></a>
<h1 id="1-创建项目"><a href="#1-创建项目" class="headerlink" title="1. 创建项目"></a>1. 创建项目</h1><h2 id="1-1-安装脚手架create-react-app"><a href="#1-1-安装脚手架create-react-app" class="headerlink" title="1.1 - 安装脚手架create-react-app"></a>1.1 - 安装脚手架create-react-app</h2><p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">npm install -g create-react-app@2.0.0-next.3e165448
</code></pre>
<h2 id="1-2-创建项目"><a href="#1-2-创建项目" class="headerlink" title="1.2 - 创建项目"></a>1.2 - 创建项目</h2><p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">create-react-app react-demo
</code></pre>
<h2 id="1-3-运行项目"><a href="#1-3-运行项目" class="headerlink" title="1.3 - 运行项目"></a>1.3 - 运行项目</h2><p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">npm start
或者
yarn start
</code></pre>
<h1 id="2-项目结构说明"><a href="#2-项目结构说明" class="headerlink" title="2. 项目结构说明"></a>2. 项目结构说明</h1><p>创建好项目之后的结构目录：<br><img src="https://pic.zhuliang.ltd/20200116095451.png-c" alt="结构目录"><br>其中：</p>
<ul>
<li><p>/public/index.html是整个项目的入口文件，我们可以在该文件中添加一些CDN资源，如jQuery等。</p>
<p>  index.html文件内容：</p>
<p>  <img src="https://pic.zhuliang.ltd/20200116095548.png-c" alt><br>  P.S.：</p>
<ul>
<li>在index.html中，有一个根容器：id=”root”</li>
<li>这个是整个项目的总容器，创建的组件最终都生成在该容器中。</li>
<li>对于该文件，一般情况下，我们不会在这个html文件中增加我们的业务代码</li>
</ul>
</li>
</ul>
<ul>
<li>src/index.js：跟index.html相关联，会将该js中声明的组件渲染到public/index.html中 “id=root” 的容器内<br>  <img src="https://pic.zhuliang.ltd/20200116095623.png-c" alt><ul>
<li>ReactDOM.render是react最基本的方法，用于将模板转换为HTML语言，并插入到指定的DOM节点。 </li>
<li>像上面的代码的意思就是把App这个组件转换成html后插入到root节点中。</li>
<li>在这里，可以将 <app> 认为是整个项目的根组件，要使用App组件，需要引入该组件，见L4（第四行）<ul>
<li>通过 import App from ‘./App’ 进行引用，默认情况下，webpack自动将文件作为js文件进行处理，所以这里在引入App.js的时候，不用显式指明 “./App.js”</li>
</ul>
</app></li>
</ul>
</li>
</ul>
<blockquote>
<p>为什么从项目结构中并看不出任何跟webpack相关的文件？</p>
</blockquote>
<h1 id="3-项目解包"><a href="#3-项目解包" class="headerlink" title="3. 项目解包"></a>3. 项目解包</h1><p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">npm run eject
</code></pre>
<p>项目解包后的入口文件、入口函数图示：<br><img src="https://pic.zhuliang.ltd/20200116095702.png-c" alt></p>
<ul>
<li>解包之后的项目无法通过  npm start 这样的命令直接启动项目（解包的同时会从node_modules中删除包）</li>
<li>此时需要运行 npm install 进行安装package.json中定义的包。</li>
</ul>
<h1 id="4-JSX语法"><a href="#4-JSX语法" class="headerlink" title="4. JSX语法"></a>4. JSX语法</h1><blockquote>
<p>脚手架创建的react项目中的App.js，默认使用了JSX语法</p>
</blockquote>
<ul>
<li>使用JSX语法需要导入 react</li>
<li>JSX语法与非JSX语法的对比：<br><img src="https://pic.zhuliang.ltd/20200116095731.png-c" alt></li>
</ul>
<h2 id="Demo"><a href="#Demo" class="headerlink" title="Demo"></a>Demo</h2><p><strong>Demo1 - 在JSX中，通过花括号 {} ，可以使用javascript表达式，如：</strong></p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">render() {
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;span&gt;hello react.&lt;/span&gt;
      &lt;div id=&quot;demo&quot;&gt;
        1+1={1 + 1} //最终结果:1+1=2
      &lt;/div&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p><strong>Demo2 - JSX中无法使用 if-else，但可以使用三元表达式来代替，如：</strong></p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">render() {
  let isDisplayOne = true;
  let one = &quot;i am One&quot;;
  let two = &quot;i am Two&quot;;
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;span&gt;hello react.&lt;/span&gt;
      &lt;div id=&quot;demo&quot;&gt;
        {isDisplayOne ? one : two} //通过三元表达式代替if-else，如果?号后面的内容过多，建议抽取后通过变量赋值
      &lt;/div&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p><strong>Demo3 - JSX中，html标签内部的注释需要用花括号括起来，如：</strong></p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">render() {
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;span&gt;hello react.&lt;/span&gt;
      &lt;div id=&quot;demo&quot;&gt;
        {/* &lt;span&gt;test annotation&lt;/span&gt; */}
      &lt;/div&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p><strong>Demo4 - JSX中，使用数组，会将数组中的内容自动按照顺序填充到html标签中，如：</strong></p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">render() {
  let arr = [
      {/*如果要在jsx中使用内联属性元素，则属性值在赋值的时候需要用双花括号括起来。*/}
    &lt;span style={{ color: 'blue' }}&gt;1.hello&lt;/span&gt;,
    &lt;span style={{ color: 'yellow' }}&gt;2.world&lt;/span&gt;
  ];
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;span&gt;hello react.&lt;/span&gt;
      &lt;div id=&quot;demo&quot;&gt;
        &lt;div&gt;{arr}&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p><strong>Demo5 - 在JSX中，html中的一些元素属性：如class，for，需要使用 className 和 htmlFor 来做代替，如：</strong></p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">render() {
  return (
    &lt;div className=&quot;App&quot;&gt;
      {/*以下内容最终生成的html为：&lt;span class=&quot;testClass&quot; for=&quot;using htmlFor&quot;&gt;hello react.&lt;/span&gt; */}
      &lt;span className=&quot;testClass&quot; htmlFor=&quot;using htmlFor&quot;&gt;hello react.&lt;/span&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p><strong>Demo6 - jsx中，属性事件</strong></p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">&lt;button onClick=&quot;XXXXX&quot;&gt;button&lt;/button&gt;
这里在定义点击事件的时候，不再是全小写的“onclick”，而是“onClick”--- C 大写。命名上，类似于camel命名
</code></pre>
<p>使用：</p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">假设在声明了如下方法：
//无参方法
sayHello(){
  console.log(&quot;say hello&quot;);
}
//带参方法
sayHelloTo(name) {
  console.log(&quot;hello &quot; + name);
}
通过按钮点击事件使用 sayHello方法
  &lt; div &gt; &lt;button onClick={this.sayHello} &gt;button&lt;/button&gt;&lt;/div &gt;
</code></pre>
<p>在调用方法的时候，需要注意以下几点：</p>
<ol>
<li>若调用的方法不带参数，如 sayHello：<ul>
<li>若调用时方法上带上了圆括号，如 onClick={this.sayHello()}，则在页面加载的时候，该方法会自动执行一遍。</li>
<li>若调用时没有带圆括号，如 onClick={this.sayHello}，则页面加载的时候，该方法不会自动执行，需要点击该按钮后才会被执行。</li>
</ul>
</li>
<li>若调用的方法带参数，如 sayHelloTo：<ul>
<li>若调用方式为：onClick={this.sayHelloTo(‘Lucy’)}，则页面加载的时候，该方法就自动执行，且之后按钮再怎么点击也无效</li>
<li>若想让带参方法不自动执行，方法有两种：<ul>
<li>1.通过箭头函数：onClick={()=&gt;this.sayHelloTo(“Lucy”)}</li>
<li>2.使用bind：onClick={this.sayHelloTo.bind(this,”Lucy”)} //第一个参数表示当前指向的对象，这里传的this表示的当前js中定义的class(因为该this是JSX中的this)，第二个参数开始就是调用方法的入参</li>
</ul>
</li>
</ul>
</li>
</ol>
<h1 id="5-组件：Component"><a href="#5-组件：Component" class="headerlink" title="5. 组件：Component"></a>5. 组件：Component</h1><p>一个简单例子：在src目录中创建如下目录和文件<br><img src="https://pic.zhuliang.ltd/20200116095805.png-c" alt></p>
<h2 id="5-1-创建自定义组件：Student-js"><a href="#5-1-创建自定义组件：Student-js" class="headerlink" title="5.1 - 创建自定义组件：Student.js"></a>5.1 - 创建自定义组件：Student.js</h2><p>Student.js：</p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">import React from &#39;react&#39;
function student(props){
    return &lt;div&gt;大家好，我是学生&lt;/div&gt;
}

export default student;
</code></pre>
<h2 id="5-2-在App-js中使用Student组件"><a href="#5-2-在App-js中使用Student组件" class="headerlink" title="5.2 - 在App.js中使用Student组件"></a>5.2 - 在App.js中使用Student组件</h2><p>App.js：</p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">导入组件：import Student from &#39;./Components/Student/Student&#39;;
使用组件：
  render() {
    return (
    &lt;div className=&quot;App&quot; htmlFor=&quot;html for for for demo&quot;&gt;
        &lt;Student /&gt;
        &lt;Student /&gt;
        &lt;Student /&gt;
    &lt;/div&gt;
    );
}
</code></pre>
<h2 id="5-3-组件中如何传值？"><a href="#5-3-组件中如何传值？" class="headerlink" title="5.3 - 组件中如何传值？"></a>5.3 - 组件中如何传值？</h2><h3 id="5-3-1-通过-props"><a href="#5-3-1-通过-props" class="headerlink" title="5.3.1 - 通过 props"></a>5.3.1 - 通过 props</h3><p>Student.js：</p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">import React from &#39;react&#39;
function student(props){
    return &lt;div&gt;大家好，我是学生：{props.name},班级：{props.class}&lt;/div&gt;
}

export default student;
</code></pre>
<p>App.js</p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">render() {
  return (
    &lt;div className=&quot;App&quot; htmlFor=&quot;html for for for demo&quot;&gt;
      &lt;Student name=&quot;A&quot; class=&quot;class_1&quot;/&gt;
      &lt;Student name=&quot;B&quot; class=&quot;class_2&quot;/&gt;
      &lt;Student name=&quot;C&quot; class=&quot;class_1&quot;/&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<h3 id="5-3-2-通过-state"><a href="#5-3-2-通过-state" class="headerlink" title="5.3.2 - 通过 state"></a>5.3.2 - 通过 state</h3><ul>
<li>什么是 state，如何使用？<ul>
<li>state是定义在Component中的一个属性，组件必须是class组件继承自Component</li>
</ul>
</li>
</ul>
<p>定义 state：</p>
<p>App.js</p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">class App extends Component {
    {/*定义state*/}
    state = {
        students:[
        {id:1, name:&quot;John&quot;, class:&quot;class_A&quot;},
        {id:2, name:&quot;Steve&quot;, class:&quot;class_C&quot;},
        {id:3, name:&quot;Trump&quot;, class:&quot;class_A&quot;},
        ]
    }

    render() {
        return (
        &lt;div className=&quot;App&quot; htmlFor=&quot;html for for for demo&quot;&gt;
            &lt;Student name={this.state.students[0].name} class={this.state.students[0].class}/&gt;
            &lt;Student name={this.state.students[1].name} class={this.state.students[1].class}/&gt;
            &lt;Student name={this.state.students[2].name} class={this.state.students[2].class}/&gt;
        &lt;/div&gt;
        );
    }
}
</code></pre>
<p>如何动态修改数据？</p>
<ul>
<li>通过 this.setState()方法</li>
</ul>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">changeStudent = () =&gt; {
  this.setState({
    students: [
      { id: 1, name: &quot;John_______&quot;, class: &quot;class_A&quot; },
      { id: 2, name: &quot;Steve&quot;, class: &quot;class_C&quot; },
      { id: 3, name: &quot;Trump&quot;, class: &quot;class_A&quot; },
    ]
  });
}

render() {
  return (
    &lt;div className=&quot;App&quot; htmlFor=&quot;html for for for demo&quot;&gt;
      &lt;Student name={this.state.students[0].name} class={this.state.students[0].class} /&gt;
      &lt;Student name={this.state.students[1].name} class={this.state.students[1].class} /&gt;
      &lt;Student name={this.state.students[2].name} class={this.state.students[2].class} /&gt;
      &lt;button onClick={this.changeStudent}&gt;修改&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>Demo1 - 数据的双向绑定：修改年级信息</p>
<p>App.js</p>
<ul>
<li><ol>
<li>增加grade信息容器</li>
</ol>
</li>
<li><ol start="2">
<li>增加输入行用于更新grade信息</li>
</ol>
</li>
</ul>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">class App extends Component {
  state = {
    students: [
      { id: 1, name: &quot;John&quot;, class: &quot;class_A&quot; },
      { id: 2, name: &quot;Steve&quot;, class: &quot;class_C&quot; },
      { id: 3, name: &quot;Trump&quot;, class: &quot;class_A&quot; },
    ],
    gradeInfo:&quot;grade one&quot;  
  }
  ...
  changeGradeInfo = (event)=&gt;{
    this.setState({
      gradeInfo:event.target.value
    })
  }

  render() {
    return (
      &lt;div className=&quot;App&quot; htmlFor=&quot;html for for for demo&quot;&gt;
        &lt;div&gt;{this.state.gradeInfo}&lt;/div&gt;
        ...
        &lt;input type=&quot;text&quot; onChange={ this.changeGradeInfo}&gt;&lt;/input&gt;
        &lt;button onClick={this.changeStudent}&gt;修改&lt;/button&gt;
      &lt;/div&gt;
    );
  }
}
</code></pre>
<p>Demo2 - 修改学生姓名</p>
<p>App.js：</p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">class App extends Component {
  ...
  changeStudentTo = (event,id) =&gt; {
    let students = this.state.students;
    let index = students.findIndex(ent=&gt;ent.id===id);
    console.log(index);
    let student = students[index];
    student.name = event.target.value
    students[index] = student;
    this.setState({
      students: students
    });
  }

  render() {
    return (
      &lt;div className=&quot;App&quot; htmlFor=&quot;html for for for demo&quot;&gt;
        &lt;div&gt;{this.state.gradeInfo}&lt;/div&gt;
        &lt;Student id={this.state.students[0].id} onChangeStudentTo={this.changeStudentTo} name={this.state.students[0].name} class={this.state.students[0].class} /&gt;
        &lt;Student id={this.state.students[1].id} onChangeStudentTo={this.changeStudentTo} name={this.state.students[1].name} class={this.state.students[1].class} /&gt;
        &lt;Student id={this.state.students[2].id} onChangeStudentTo={this.changeStudentTo} name={this.state.students[2].name} class={this.state.students[2].class} /&gt;
        &lt;input type=&quot;text&quot; onChange={ this.changeGradeInfo}&gt;&lt;/input&gt;
        &lt;button onClick={this.changeStudent}&gt;修改&lt;/button&gt;
      &lt;/div&gt;
    );
  }
}
</code></pre>
<p>Student.js：</p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">
  import React from &#39;react&#39;
  function student(props) {
      return (
          &lt;div&gt;
              &lt;div&gt;大家好，我是学生：{props.name},班级：{props.class}&lt;/div&gt;
              &lt;input type=&quot;text&quot; onChange={(e)=&gt;props.onChangeStudentTo(e, props.id)} /&gt;
          &lt;/div&gt;);
  }
  export default student;
</code></pre>
<blockquote>
<p>这里需要注意下，react的event和我们平时认为的JS的event不一样，相关文档见此： <a href="https://reactjs.org/docs/events.html" target="_blank" rel="noopener">https://reactjs.org/docs/events.html</a></p>
<ul>
<li>什么时候用 state？<ul>
<li>需要动态改变组建内值的时候</li>
<li>需要使用组件的生命周期函数的时候</li>
</ul>
</li>
</ul>
</blockquote>
<h1 id="6-React中的样式"><a href="#6-React中的样式" class="headerlink" title="6. React中的样式"></a>6. React中的样式</h1><h2 id="6-1-通过-import-导入样式"><a href="#6-1-通过-import-导入样式" class="headerlink" title="6.1 - 通过 import 导入样式"></a>6.1 - 通过 import 导入样式</h2><p>在Student.js同级目录创建Student.css</p>
<p></p><p class="code-caption" data-lang="css" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="css">Student.css
  div{
      color:blue;
  }
</code></pre>
<p>在Student.js中使用该样式</p>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">import &#39;./Student.css&#39;
</code></pre>
<h2 id="6-2-直接在组件中定义样式"><a href="#6-2-直接在组件中定义样式" class="headerlink" title="6.2 - 直接在组件中定义样式"></a>6.2 - 直接在组件中定义样式</h2><p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">Student.js
  import React from &#39;react&#39;
  var myStyle = {
      color:&quot;orange&quot;,
      fontSize:&quot;22px&quot;
  }

  function student(props) {

      return (
          &lt;div&gt;
              &lt;div style={myStyle}&gt;大家好，我是学生：{props.name},班级：{props.class}&lt;/div&gt;
              &lt;input type=&quot;text&quot; onChange={props.onChangeStudentTo.bind(this,props.id)}&gt;&lt;/input&gt;
          &lt;/div&gt;);
  }
  export default student;
</code></pre>
<h1 id="7-流程控制语句"><a href="#7-流程控制语句" class="headerlink" title="7. 流程控制语句"></a>7. 流程控制语句</h1><h2 id="7-1-条件判断语句"><a href="#7-1-条件判断语句" class="headerlink" title="7.1 - 条件判断语句"></a>7.1 - 条件判断语句</h2><ul>
<li>一种是在JSX中使用三元表达式</li>
</ul>
<p></p><p class="code-caption" data-lang="html" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="html">JSX语法
        &lt;div&gt;{this.state.isShowGradeInfo?this.state.gradeInfo:&quot;&quot;}&lt;/div&gt;
</code></pre>
<ul>
<li>一种是在JSX语法外，先把需要判断的东西计算出结果后，直接使用结果</li>
</ul>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">render() {
  let gradeInfo = null;
  if(this.state.isShowGradeInfo){
    gradeInfo = this.state.gradeInfo;
  }
  return (
    &lt;div className=&quot;App&quot; htmlFor=&quot;html for for for demo&quot;&gt;
      ...
      &lt;div&gt;{gradeInfo}&lt;/div&gt;
      ...
    &lt;/div&gt;
  );
}
</code></pre>
<h2 id="7-2-循环语句"><a href="#7-2-循环语句" class="headerlink" title="7.2 - 循环语句"></a>7.2 - 循环语句</h2><ul>
<li>一种是常规的for循环</li>
</ul>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">render() {
  ...
  var studentArray = [];
  for(let i=0;i&lt;this.state.students.length;i++){        
      studentArray.push(&lt;Student id={this.state.students[i].id} onChangeStudentTo={this.changeStudentTo} name={this.state.students[i].name} class={this.state.students[i].class} /&gt;)
  }
  return (
    &lt;div className=&quot;App&quot; htmlFor=&quot;html for for for demo&quot;&gt;
      ...
      {/* {studentArray} */}
      {this.state.students.map(student=&gt;{
        return &lt;Student id={student.id} onChangeStudentTo={this.changeStudentTo} name={student.name} class={student.class} /&gt;
      })}
      ...
    &lt;/div&gt;
  );
}
</code></pre>
<ul>
<li>一种是使用map方法（推荐）</li>
</ul>
<p></p><p class="code-caption" data-lang="javascript" data-line_number="backend" data-trim_indent="backend" data-label_position="outer" data-labels_left="Code" data-labels_right=":" data-labels_copy="Copy Code"><span class="code-caption-label"></span></p><p></p>
<pre><code class="javascript">render() {
  ...

  return (
    &lt;div className=&quot;App&quot; htmlFor=&quot;html for for for demo&quot;&gt;
      ...
      {
        this.state.students.map(student=&gt;{
        return &lt;Student id={student.id} onChangeStudentTo={this.changeStudentTo} name={student.name} class={student.class} /&gt;
        });
      }
      ...
    &lt;/div&gt;
  );
}
</code></pre>

      

      <div>
        
        <div style="background-color: rgb(255, 23, 0);user-select: auto;height: 3px;width:100%;margin-top: 40px;margin-bottom:15px;"></div>

<!-- <p>常言道：学然后知不足，教然后知困。</p>
<p>我知道你的焦虑，一起共进加油：P</p>
<p>关不关注都无所谓，会根据生活节奏紧凑度定期分享些开发经验、搬砖生涯、痛点、感悟。</p>
<p>
        <img src="https://pic.zhuliang.ltd/20191213133908.gif" alt="欢迎关注我的订阅号：P" />
</p> -->
<ul class="post-copyright" style="margin-left:0px;">
    <li class="post-copyright-author">
        <strong>本文作者：</strong>积慕
    </li>
    <li class="post-copyright-link">
        <strong>本文链接：</strong>
        <a href="/2018/08/frontend/hello-react.html" title="部门内部培训 react 系列讲义一：React 入门">https://blog.zhuliang.ltd/2018/08/frontend/hello-react.html</a>
    </li>
    <li class="post-copyright-license">
        <strong>版权： </strong>
        本站文章均采用 <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/cn/" rel="external nofollow"
            target="_blank">CC BY-NC-SA 3.0 CN</a> 许可协议，请勿用于商业，转载注明出处！
    </li>
</ul>
        
      </div>
    </div>

    <footer>
      
      
  
  <div class="categories">
    <a href="/categories/frontend/">frontend</a>
  </div>

      
  
  <div class="tags">
    <a href="/tags/教程/">教程</a>, <a href="/tags/react/">react</a>, <a href="/tags/培训讲义/">培训讲义</a>
  </div>

      <!-- 
  <div class="addthis addthis_toolbox addthis_default_style">
    
    
      <a class="addthis_button_tweet"></a>
    
    
      <a class="addthis_button_google_plusone" g:plusone:size="medium"></a>
    
    
      <a class="addthis_button_pinterest_pinit" pi:pinit:layout="horizontal"></a>
    
    <a class="addthis_counter addthis_pill_style"></a>
  </div>
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js"></script>
 -->
      
      <div class="clearfix"></div>
    </footer>
  </div>
</article>

<!-- 
<section id="comment">
  <h1 class="title">留言</h1>

  <div id="vcomments" style="background-color: #fff"></div>
  <script>
    new Valine({
      el: '#vcomments',
      appId: 'aTPKmG6tjDo3CbIXzAPzrj4X-gzGzoHsz',
      appKey: 'hNgWFneNpEcMnBJclPQnDgsd',
      notify: true,
      verify: true, //验证码
      avatar: 'monsterid', //https://valine.js.org/avatar.html
      placeholder: '请输入你的评论'
    })
  </script>
</section>
 --> <!--启用/关闭 LeanCloud 评论--></div></div>
    <aside id="sidebar" class="alignright">
  
<div class="widget tag">
  <h3 class="title"><i class="iconfont icon-category"></i>&nbsp;&nbsp;分类</h3>
  <ul class="entry">
  
    <li><a href="/categories/Obsidian/">Obsidian</a><small>1</small></li>
  
    <li><a href="/categories/PowerUser/">PowerUser</a><small>4</small></li>
  
    <li><a href="/categories/backend/">backend</a><small>57</small></li>
  
    <li><a href="/categories/frontend/">frontend</a><small>9</small></li>
  
    <li><a href="/categories/operations/">operations</a><small>5</small></li>
  
    <li><a href="/categories/提前退休/">提前退休</a><small>2</small></li>
  
  </ul>
</div>


  
<div class="widget tag">
  <h3 class="title"><i class="iconfont icon-new3"></i>&nbsp;&nbsp;最新文章</h3>
  <ul class="entry">
    
      <li>
        <a href="/2024/11/PowerUser/install-docker-in-pve-lxc.html">1. 通过 PVE LXC 搭建 docker 环境</a>
      </li>
    
      <li>
        <a href="/2024/11/Obsidian/obsidian-render-pie-chart.html">2. 2 套用于 obsidian 的生成时间占用饼图脚本示例，基于 templater， charts，echarts+dataview</a>
      </li>
    
      <li>
        <a href="/2024/10/PowerUser/fix-ios18-samba-readonly-issue.html">3. 解决 ios 18（包括ipadOS 18） 下通过文件(files app)连接 samba 服务器，目录变成只读权限的问题</a>
      </li>
    
      <li>
        <a href="/2023/07/operations/how-to-use-pm2.html">4. PM2 的安装、配置和使用</a>
      </li>
    
      <li>
        <a href="/2023/07/backend/expose-intranet-netcoreapi-to-internet.html">5. 通过 DDNS+显性URL 把内网部署的.NET CORE WEBAPI 项目暴露到公网中</a>
      </li>
    
  </ul>
</div>


  
<div class="widget tag">
  <h3 class="title"><i class="iconfont icon-tag"></i>&nbsp;&nbsp;标签</h3>
  <ul class="entry">
  
    <li><a href="/tags/net-core/">.net core</a><small>12</small></li>
  
    <li><a href="/tags/Debian/">Debian</a><small>2</small></li>
  
    <li><a href="/tags/Docker/">Docker</a><small>1</small></li>
  
    <li><a href="/tags/Elasticsearch/">Elasticsearch</a><small>35</small></li>
  
    <li><a href="/tags/Elasticsearch-Nest系列/">Elasticsearch.Nest系列</a><small>35</small></li>
  
    <li><a href="/tags/Obsidian/">Obsidian</a><small>1</small></li>
  
    <li><a href="/tags/PVE/">PVE</a><small>2</small></li>
  
    <li><a href="/tags/StackExchange-Redis系列/">StackExchange.Redis系列</a><small>12</small></li>
  
    <li><a href="/tags/centos/">centos</a><small>3</small></li>
  
    <li><a href="/tags/flex/">flex</a><small>1</small></li>
  
    <li><a href="/tags/ios/">ios</a><small>1</small></li>
  
    <li><a href="/tags/javascript/">javascript</a><small>1</small></li>
  
    <li><a href="/tags/linux/">linux</a><small>4</small></li>
  
    <li><a href="/tags/nginx/">nginx</a><small>2</small></li>
  
    <li><a href="/tags/nuget/">nuget</a><small>2</small></li>
  
    <li><a href="/tags/react/">react</a><small>6</small></li>
  
    <li><a href="/tags/styled-components/">styled-components</a><small>1</small></li>
  
    <li><a href="/tags/内网穿透/">内网穿透</a><small>4</small></li>
  
    <li><a href="/tags/培训讲义/">培训讲义</a><small>2</small></li>
  
    <li><a href="/tags/基础知识/">基础知识</a><small>2</small></li>
  
    <li><a href="/tags/性能优化/">性能优化</a><small>2</small></li>
  
    <li><a href="/tags/教程/">教程</a><small>64</small></li>
  
    <li><a href="/tags/理财/">理财</a><small>2</small></li>
  
    <li><a href="/tags/生命周期/">生命周期</a><small>1</small></li>
  
    <li><a href="/tags/经验/">经验</a><small>4</small></li>
  
  </ul>
</div>


  
  <script type="text/javascript" charset="utf-8" src="/js/tagcloud.js"></script>
  <script type="text/javascript" charset="utf-8" src="/js/tagcanvas.js"></script>
  <div class="widget tag">
    <h3 class="title"><i class="iconfont icon-cloud1"></i>&nbsp;&nbsp;标签云</h3>
    <div id="myCanvasContainer" class="widget tagcloud">
      <canvas width="250" height="250" id="resCanvas" style="width:100%">
        <a href="/tags/net-core/" style="font-size: 17.14px;">.net core</a> <a href="/tags/Debian/" style="font-size: 11.43px;">Debian</a> <a href="/tags/Docker/" style="font-size: 10px;">Docker</a> <a href="/tags/Elasticsearch/" style="font-size: 18.57px;">Elasticsearch</a> <a href="/tags/Elasticsearch-Nest系列/" style="font-size: 18.57px;">Elasticsearch.Nest系列</a> <a href="/tags/Obsidian/" style="font-size: 10px;">Obsidian</a> <a href="/tags/PVE/" style="font-size: 11.43px;">PVE</a> <a href="/tags/StackExchange-Redis系列/" style="font-size: 17.14px;">StackExchange.Redis系列</a> <a href="/tags/centos/" style="font-size: 12.86px;">centos</a> <a href="/tags/flex/" style="font-size: 10px;">flex</a> <a href="/tags/ios/" style="font-size: 10px;">ios</a> <a href="/tags/javascript/" style="font-size: 10px;">javascript</a> <a href="/tags/linux/" style="font-size: 14.29px;">linux</a> <a href="/tags/nginx/" style="font-size: 11.43px;">nginx</a> <a href="/tags/nuget/" style="font-size: 11.43px;">nuget</a> <a href="/tags/react/" style="font-size: 15.71px;">react</a> <a href="/tags/styled-components/" style="font-size: 10px;">styled-components</a> <a href="/tags/内网穿透/" style="font-size: 14.29px;">内网穿透</a> <a href="/tags/培训讲义/" style="font-size: 11.43px;">培训讲义</a> <a href="/tags/基础知识/" style="font-size: 11.43px;">基础知识</a> <a href="/tags/性能优化/" style="font-size: 11.43px;">性能优化</a> <a href="/tags/教程/" style="font-size: 20px;">教程</a> <a href="/tags/理财/" style="font-size: 11.43px;">理财</a> <a href="/tags/生命周期/" style="font-size: 10px;">生命周期</a> <a href="/tags/经验/" style="font-size: 14.29px;">经验</a>
      </canvas>
    </div>
  </div>




</aside>
    <div class="clearfix"></div>
  </div>
  <footer id="footer" class="inner"><div class="alignleft">

  
  &copy; 2018 - 2024 &nbsp;<a href='/about'>积慕</a>
  
  &nbsp;&nbsp;<a href='https://www.cnblogs.com/deepthought/'>我的博客园地址</a>
  &nbsp;&nbsp;finalclassic#outlook.com
</div>

<div class="clearfix"></div>
<div>
  本站主题基于：<a href='https://github.com/hexojs/hexo-theme-light' rel="external nofollow">hexo-theme-light</a>
</div>
<div id="busuanzi_container_site_pv">
  本站总访问量&nbsp;<span id="busuanzi_value_site_pv"></span>&nbsp;次
</div>
<div style="width:300px;margin:0 auto; padding:20px 0;">
  <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=31011702004805" style="display:inline-block;text-decoration:none;height:20px;line-height:20px;">
    <img src="https://pic.zhuliang.ltd/20200102164648.png" style="float:left;"><p style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; color:#939393;">沪公网安备 31011702004805号</p></a>
</div></footer>
  <script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/jquery.imagesloaded.min.js"></script>
<script src="/js/gallery.js"></script>




<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
(function($){
  $('.fancybox').fancybox();
})(jQuery);
</script>


<script type="text/javascript">
hljs.initHighlightingOnLoad();
</script>

<!-- <script src="/js/busuanzi.pure.mini.js"></script> -->
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?ea793b9c8d6b31df666a6bc15038e246";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>
<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        }
        else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>
</body>
</html>
